package com.tencent.mars.xlogsample;

import com.tencent.mars.xlogsample.LogInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LogcatToXLog {

    // 日志级别常量定义，与常见日志级别对应（这里可根据XLog具体的日志级别设定进行调整）
    public static final int LEVEL_DEBUG = 1;
    public static final int LEVEL_VERBOSE = 2;
    public static final int LEVEL_INFO = 3;
    public static final int LEVEL_WARNING = 4;
    public static final int LEVEL_ERROR = 5;
    public static final int LEVEL_FATAL = 6;

    // 解析logcat内容并返回LogInfo对象的方法
    public static LogInfo convertLogcatToLogInfo(String logcatContent) {
        // 使用正则表达式拆分logcat内容并提取关键信息
        Pattern pattern = Pattern.compile("^(\\S+ \\S+)\\s+(\\d+)-(\\d+)\\s+(\\S+)\\s+(\\S)\\s+(.*)$");
        Matcher matcher = pattern.matcher(logcatContent);

        if (matcher.find()) {
            // 提取进程ID并转换为整数类型
            int processId = Integer.parseInt(matcher.group(2));

            // 提取线程ID并转换为整数类型
            int threadId = Integer.parseInt(matcher.group(3));

            // 提取日志级别并转换为对应的级别常量
            String logLevel = matcher.group(5);
            int level;
            switch (logLevel) {
                case "D":
                    level = LEVEL_DEBUG;
                    break;
                case "V":
                    level = LEVEL_VERBOSE;
                    break;
                case "I":
                    level = LEVEL_INFO;
                    break;
                case "W":
                    level = LEVEL_WARNING;
                    break;
                case "E":
                    level = LEVEL_ERROR;
                    break;
                case "F":
                    level = LEVEL_FATAL;
                    break;
                default:
                    // 如果日志级别不是已知的类型，可根据实际需求进行其他处理，比如忽略或者转换为对应的其他日志级别
                    System.out.println("不支持的日志级别：" + logLevel);
                    return null;
            }

            // 提取日志标签
            String tag = matcher.group(4);

            // 提取具体日志消息
            String logMessage = matcher.group(6).trim();

            // 创建并返回LogInfo对象，设置好相应的属性值
            return new LogInfo()
                    .setLevel(level)
                    .setTag(tag)
                    .setFilename("")
                    .setFuncname("")
                    .setLine(0)
                    .setPid(processId)
                    .setTid(threadId)
                    .setMaintid(threadId)
                    .setLog(logMessage);
        }

        return null;
    }
}